﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using Medianamik.Core;

namespace Medianamik.UI.Controls
{
    public class MedianamikLanguagePicker : BaseMedianamikControl
    {
        private readonly System.Web.UI.WebControls.DropDownList _ddList = new System.Web.UI.WebControls.DropDownList()
        {
            ID = ControlToValidateId,
            CssClass = "SelectList"
        };

        public BasePage BasePage
        {
            get
            {
                return (BasePage)base.Page;
            }
        }

        public override object GetValue()
        {
            return _ddList.SelectedValue;
        }

        public override void SetValue(object value)
        {
            var str = "";

            if (value != null)
                str = value.ToString();

            var index = 0;

            for (var i = 0; i < _ddList.Items.Count; i++)
            {
                if (_ddList.Items[i].Value.EqualsIgnoreCase(str))
                {
                    index = i;
                    break;
                }
            }

            _ddList.SelectedIndex = index;
        }

        public override Type TypeOfValue
        {
            get { return typeof(String); }
        }

        protected override void CreateControlHierarchy(bool pUseDataSource)
        {
            Controls.Add(_ddList);

            if (pUseDataSource)
            {
                _ddList.Items.Insert(0, string.Empty);

                ConfigManager.GetMedianamikCultures()
                    .ForEach(c => _ddList.Items
                        .Add(new ListItem(c.CultureInfo.DisplayName, c.CultureName)));

                SetValue(DataSource);
            }
        }
    }
}
